<template>
  <div class="news-board">
    <div class="news-header">
      <h1>社区新闻</h1>
      <div class="news-filter">
        <span>筛选：</span>
        <button 
          v-for="category in displayCategories" 
          :key="category.value"
          :class="['filter-btn', { active: currentCategory === category.value }]"
          @click="currentCategory = category.value"
        >
          {{ category.label }}
        </button>
      </div>
    </div>

    <div class="news-content">
      <div v-if="loading" class="loading">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
      
      <div v-else-if="error" class="error-message">
        {{ error }}
      </div>
      
      <div v-else-if="filteredNews.length === 0" class="empty-state">
        <p>暂无{{ getCategoryLabel(currentCategory) }}相关新闻</p>
      </div>
      
      <div v-else class="news-grid">
        <div v-for="news in filteredNews" :key="news.id" class="news-card">
          <div class="news-image">
            <img :src="news.imageUrl" :alt="news.title">
            <span class="news-category">{{ getCategoryLabel(news.category) }}</span>
            <span v-if="news.category === userPreference" class="recommend-tag">推荐</span>
          </div>
          <div class="news-details">
            <h3>{{ news.title }}</h3>
            <p class="news-excerpt">{{ news.content.substring(0, 100) }}...</p>
            <div class="news-meta">
              <span class="news-date">{{ formatDate(news.publishDate) }}</span>
              <span class="news-author">{{ news.author }}</span>
            </div>
            <button class="read-more" @click="showNewsDetail(news)">阅读全文</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 新闻详情弹窗 -->
    <div v-if="selectedNews" class="news-modal" @click.self="selectedNews = null">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h2>{{ selectedNews.title }}</h2>
          <button class="close-btn" @click="selectedNews = null">×</button>
        </div>
        <div class="modal-body">
          <img :src="selectedNews.imageUrl" :alt="selectedNews.title" class="news-detail-image">
          <div class="news-meta">
            <span class="news-category-badge">{{ getCategoryLabel(selectedNews.category) }}</span>
            <span class="news-date">{{ formatDate(selectedNews.publishDate) }}</span>
            <span class="news-author">作者: {{ selectedNews.author }}</span>
          </div>
          <div class="news-content-full">
            {{ selectedNews.content }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'NewsBoard',
  data() {
    return {
      newsList: [],
      loading: true,
      error: null,
      currentCategory: 'all',
      selectedNews: null,
      userPreference: '',
      newsCategories: [
        { value: 'all', label: '全部' },
        { value: 'politics', label: '政治' },
        { value: 'sports', label: '体育' },
        { value: 'technology', label: '科技' },
        { value: 'entertainment', label: '娱乐' },
        { value: 'business', label: '商业' },
        { value: 'health', label: '健康' },
        { value: 'science', label: '科学' },
        { value: 'education', label: '教育' }
      ]
    }
  },
  computed: {
    filteredNews() {
      if (this.currentCategory === 'all') {
        return this.newsList;
      }
      return this.newsList.filter(news => news.category === this.currentCategory);
    },
    displayCategories() {
      return this.newsCategories.map(category => ({
        ...category,
        label: category.value === this.userPreference ? '推荐' : category.label
      }));
    }
  },
  methods: {
    async fetchNews() {
      this.loading = true;
      this.error = null;
      
      try {
        // 获取当前用户信息
        const user = JSON.parse(localStorage.getItem('user') || '{}');
        
        if (!user || !user.ownerId) {
          throw new Error('用户信息不存在，请重新登录');
        }
        
        // 获取用户详细信息
        const userResponse = await fetch(`http://localhost:8080/api/owners/${user.ownerId}`);
        if (!userResponse.ok) throw new Error('获取用户信息失败');
        const userDetail = await userResponse.json();
        
        // 获取用户的新闻偏好
        this.userPreference = userDetail.newsPreferences || '';
        console.log('用户新闻偏好:', this.userPreference);
        
        // 获取员工数据作为新闻作者
        const staffResponse = await fetch('http://localhost:8080/api/staff');
        if (!staffResponse.ok) throw new Error('获取员工数据失败');
        const staffList = await staffResponse.json();
        
        // 模拟新闻数据
        this.newsList = this.generateNewsData(staffList);
        
        // 如果用户有偏好，自动筛选
        if (this.userPreference && this.userPreference !== 'all') {
          this.currentCategory = this.userPreference;
          console.log('已根据用户偏好设置当前分类:', this.currentCategory);
        }
      } catch (err) {
        console.error('Error fetching news:', err);
        this.error = err.message || '获取新闻失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    generateNewsData(staffList) {
      // 模拟新闻数据
      const categories = ['politics', 'sports', 'technology', 'entertainment', 'business', 'health', 'science', 'education'];
      const newsData = [];
      
      // 为每个类别生成2-3条新闻
      categories.forEach(category => {
        const count = Math.floor(Math.random() * 2) + 2; // 2-3条
        
        for (let i = 0; i < count; i++) {
          const staff = staffList[Math.floor(Math.random() * staffList.length)] || { name: '社区编辑' };
          
          newsData.push({
            id: newsData.length + 1,
            title: this.getNewsTitle(category),
            content: this.getNewsContent(category),
            category: category,
            author: staff.name,
            publishDate: this.getRandomDate(),
            imageUrl: this.getNewsImage(category)
          });
        }
      });
      
      return newsData;
    },
    
    getNewsTitle(category) {
      const titles = {
        politics: ['社区治理新政策', '业主委员会选举结果公布', '物业管理条例修订'],
        sports: ['社区运动会圆满结束', '健身中心新增设施', '游泳池夏季开放时间调整'],
        technology: ['智能家居系统升级', '社区WiFi覆盖范围扩大', '安防系统技术更新'],
        entertainment: ['周末电影之夜活动预告', '社区才艺展示大赛', '儿童娱乐区改造完成'],
        business: ['社区商业街招商公告', '物业费用调整说明', '社区经济发展规划'],
        health: ['流感防控指南', '社区医疗服务中心开放', '健康讲座系列活动'],
        science: ['垃圾分类新标准', '节能减排倡议', '社区环保项目启动'],
        education: ['社区图书馆新书到达', '暑期儿童教育活动', '成人继续教育课程']
      };
      
      const categoryTitles = titles[category] || ['社区新闻'];
      return categoryTitles[Math.floor(Math.random() * categoryTitles.length)];
    },
    
    getNewsContent(category) {
      return `这是一篇关于${this.getCategoryLabel(category)}的详细新闻报道。本文介绍了最新的发展动态和相关信息，为社区居民提供有价值的参考。
      
社区一直致力于提供高质量的生活环境和服务，此次${this.getCategoryLabel(category)}相关的举措将进一步提升居民的生活品质和满意度。

具体内容包括：首先，社区将投入更多资源用于${this.getCategoryLabel(category)}领域的建设和完善；其次，将组织相关活动促进居民参与和交流；最后，将建立长效机制确保相关工作持续推进。

我们诚挚邀请所有居民积极参与，共同建设美好社区。如有任何建议或意见，请随时与物业管理处联系。`;
    },
    
    getNewsImage(category) {
      const images = {
        politics: 'https://img.freepik.com/free-photo/group-people-working-together-office_23-2149800867.jpg',
        sports: 'https://img.freepik.com/free-photo/sports-tools_53876-138077.jpg',
        technology: 'https://img.freepik.com/free-photo/medium-shot-man-wearing-vr-glasses_23-2149126949.jpg',
        entertainment: 'https://img.freepik.com/free-photo/excited-audience-watching-confetti-fireworks-having-fun-music-festival-night-copy-space_637285-559.jpg',
        business: 'https://img.freepik.com/free-photo/business-people-shaking-hands-together_53876-30568.jpg',
        health: 'https://img.freepik.com/free-photo/doctor-with-stethoscope-hands-hospital-background_1423-1.jpg',
        science: 'https://img.freepik.com/free-photo/scientist-working-laboratory_23-2148880401.jpg',
        education: 'https://img.freepik.com/free-photo/medium-shot-woman-teaching-class_23-2149038403.jpg'
      };
      
      return images[category] || 'https://img.freepik.com/free-photo/aerial-view-residence-building_23-2149360330.jpg';
    },
    
    getRandomDate() {
      const start = new Date(2024, 0, 1);
      const end = new Date();
      return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
    },
    
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    },
    
    getCategoryLabel(category) {
      if (category === this.userPreference) {
        return '推荐';
      }
      const found = this.newsCategories.find(c => c.value === category);
      return found ? found.label : '其他';
    },
    
    showNewsDetail(news) {
      this.selectedNews = news;
    }
  },
  created() {
    this.fetchNews();
  }
}
</script>

<style scoped>
.news-board {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.news-header {
  margin-bottom: 30px;
}

.news-header h1 {
  font-size: 2rem;
  color: var(--text-color);
  margin-bottom: 20px;
}

.news-filter {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.news-filter span {
  color: var(--gray);
  font-weight: 500;
}

.filter-btn {
  background: white;
  border: 1px solid #e2e8f0;
  border-radius: 20px;
  padding: 6px 16px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-btn.active {
  background: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.filter-btn:hover:not(.active) {
  background: #f8f9fa;
}

.news-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 25px;
}

.news-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.news-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.news-image {
  position: relative;
  height: 200px;
}

.news-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.news-category {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.news-details {
  padding: 20px;
}

.news-details h3 {
  margin: 0 0 15px 0;
  font-size: 1.2rem;
  color: var(--text-color);
}

.news-excerpt {
  color: var(--gray);
  margin-bottom: 15px;
  line-height: 1.5;
}

.news-meta {
  display: flex;
  justify-content: space-between;
  color: var(--gray);
  font-size: 0.85rem;
  margin-bottom: 15px;
}

.read-more {
  background: var(--primary-color);
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s ease;
}

.read-more:hover {
  background: var(--secondary-color);
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 20px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message, .empty-state {
  text-align: center;
  padding: 50px 0;
  color: var(--gray);
}

/* 新闻详情弹窗 */
.news-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: var(--gray);
}

.modal-body {
  padding: 20px;
}

.news-detail-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 20px;
}

.news-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.news-category-badge {
  background: var(--primary-color);
  color: white;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 0.8rem;
}

.news-content-full {
  line-height: 1.8;
  color: var(--text-color);
  white-space: pre-line;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .news-grid {
    grid-template-columns: 1fr;
  }
  
  .news-filter {
    justify-content: center;
  }
  
  .modal-content {
    width: 95%;
  }
}

.recommend-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #ff4757;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.7rem;
  font-weight: bold;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
</style> 